import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    SectionList,
    TouchableOpacity,
    DeviceEventEmitter,
    TextInput, Alert,
    Modal
} from 'react-native';
import {Card} from 'react-native-shadow-cards';
import QRCode from 'react-native-qrcode-svg';
import Styles from './Styles';
import CommonDialog from 'react-native-dialogs-master';
import app from '../../../app.json';
import Ugame from '../../../Ugame';
import Httpc from "../../utils/Httpc";
import REQUEST from "../../../REQUEST";
import styles from "../Lists/styles";

import ImagePicker from 'react-native-image-crop-picker';
import DialogSelected from '../../utils/AlertSelected/AlertSelected';

const { width, height } = Dimensions.get('window');
// 初始化总数据

export default class Userinfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            old_nick:null,
            new_nick:null,
            headimage:null,
            isSend:false,
            isShow:false,
            toastModelVisible:false,
            message:'message',
        };
        this.showAlertSelected = this.showAlertSelected.bind(this);
        this.callbackSelected = this.callbackSelected.bind(this);
    }
    static navigationOptions = {
        title: '个人资料',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: '#cc0033',
            paddingTop:18,
        },
        headerTintColor: '#fff',
        headerTitleStyle: {

        },
    }
    componentWillMount(){
        //组件将要被加载到视图之前调用
        const { navigation } = this.props;
        const old_nick = navigation.getParam("nick");
        const headimage = navigation.getParam("headimage");
        this.setState({
            old_nick:old_nick,
            new_nick:old_nick,
            headimage:headimage
        })
    }
    componentDidMount(){
        // 在调用了render方法，组件加载成功并被成功渲染出来之后，所要执行的后续操作，一般都会在这个函数中进行，比如经常要面对的网络请求等加载数据操作
        // *** 因为UI已经成功渲染，而且这里面是异步的，所以放在这个函数进行数据的请求等复杂的操作，不会出现UI错误**
        let navigation =this.props.navigation;
        // Ugame.isLogin(function () {
        //
        // },function () {
        //     navigation.navigate('Login')
        // })
    }
    showAlertSelected(){
        this.dialog.show("请选择照片",  ["拍照", "图库"], '#333333', this.callbackSelected);
    }
    // 回调
    callbackSelected(i){
        switch (i){
            case 0: // 拍照
                console.log("拍照");
                //this.takePhoto();
                break;
            case 1: // 图库
                console.log("图库");
                this.pickSingleBase64(true, true);
                //this.pickMultiple();
                break;
        }
    }
    pickSingleBase64(cropit, circular=false) {
        ImagePicker.openPicker({
            width: 300,
            height: 300,
            cropping: cropit,
            cropperCircleOverlay: circular,
            compressImageMaxWidth: 640,
            compressImageMaxHeight: 480,
            compressImageQuality: 0.5,
            includeBase64: true,
            includeExif: true,
        }).then(image => {
            this.setState({
                headimage: `data:${image.mime};base64,`+ image.data,
            });
            Httpc.postFormData(REQUEST.SetUserImage,{head:image.data},function (res) {
                this._showToast(res.Message);
                if(res.StatusCode!=1){
                    return;
                }
                DeviceEventEmitter.emit('updateLogin',{});
            }.bind(this));
        }).catch(e => {
            console.log(e);
            //Alert.alert(e.message ? e.message : e);
        });
    }


    nickChange(new_nick){
        this.setState({
            new_nick:new_nick,
        });
    }
    on_do_set_nick(){
        if(this.state.new_nick.trim().length==0){
            this.do_toast('昵称不能为空',500);
            return;
        }
        Httpc.get(REQUEST.SetUserNick,{token:Ugame.info.Token,nickname:this.state.new_nick},function (res) {
            this.do_toast(res.Message,500);
            if(res.StatusCode!=1){
                return;
            }
            DeviceEventEmitter.emit('updateLogin',{});
            this.setState({
                old_nick:this.state.new_nick
            })
        }.bind(this));
    }
    showSubmit(){
        return (
            <TouchableOpacity onPress={() => {this.on_do_set_nick()}}>
                <View style={Styles.login_btn}>
                    <Text style={{color:'#ffffff',fontSize:16}}>确认</Text>
                </View>
            </TouchableOpacity>
        );
    }
    do_toast=(str,time)=>{
        this.setState({
            message:str,
            toastModelVisible:true
        });
        setTimeout(()=>{
            this.setState({
                message:'',
                toastModelVisible:false
            });
        },time);
    }
    toast=()=>{
        return (
            <Modal
            animationType="fade"
            transparent={true}
            visible={this.state.toastModelVisible}
            onRequestClose={() => {
                this.setState({
                    toastModelVisible:false
                });
            }}
            >
            <View style={{flexDirection:'row',justifyContent:'center',position:'absolute',bottom:100,width:width}}>
                <Text style={{backgroundColor:'rgba(0,0,0,0.5)',color:'#ffffff',borderRadius:10,height:40,lineHeight:40, paddingLeft:20,paddingRight:20}}>{this.state.message}</Text>
            </View>
            </Modal>
        );
    }
    render() {
        let user_head = require('../../image/js_img_user_head.png');
        let headimage = this.state.headimage;
        if(!!headimage){
            user_head = {uri:headimage};
        }
        return (
            <View style={Styles.container}>
                <StatusBar translucent={ true } backgroundColor="transparent" />
                <TouchableOpacity onPress={() => {this.showAlertSelected();}}>
                    <View style={Styles.item}>
                        <Text>头像</Text>
                        <View style={Styles.info}>
                            <Image resizeMode="cover" style={{width:50,height:50,borderRadius:50}} source={user_head} />
                        </View>
                        <Image resizeMode="cover" style={Styles.jt} source={require('../../image/js_img_list_jump.png')}/>
                    </View>
                </TouchableOpacity>
                <View style={Styles.item}>
                    <Text>昵称</Text>
                    <View style={Styles.info}>
                        <TextInput
                            style={{textAlign:'right',height:30,padding:0}}
                            placeholder="请输入昵称"
                            editable={!this.state.old_nick.length>0}//是否可编辑
                            placeholderTextColor="#CCC"
                            onChangeText={this.nickChange.bind(this)}
                            value={this.state.new_nick}
                            //onEndEditing={this.dissmissKeyboard.bind(this)}
                        />
                    </View>
                    <Image resizeMode="cover" style={Styles.jt} source={require('../../image/js_img_list_jump.png')}/>
                </View>
                {this.state.old_nick.length==0 ? this.showSubmit():null}

                <DialogSelected ref={(dialog)=>{
                    this.dialog = dialog;
                }} />
                {this.toast()}
            </View>
        )
    }
}

class Toast extends React.Component{
    constructor(props){
        super(props);
        this.timer="";
        this.state={
            times:2
        }
    }
    componentDidMount() {
        this.timer=setInterval(() => {
            if(this.state.times<=1){
                clearInterval(this.timer)
                this.props.onclick()
            }else{
                this.setState({times:this.state.times-1})
            }
        },1000);
    }
    componentWillUnmount() {
        clearInterval(this.timer);
    }
    render(){
        return(
            <View>
            </View>
        )
    }
}